package com.ofps.forms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ofps.forms.common.utils.R;
import com.ofps.forms.common.utils.TokenUtil;
import com.ofps.forms.mapper.AnswerRadioMapper;
import com.ofps.forms.domain.AnswerRadio;
import com.ofps.forms.domain.Option;
import com.ofps.forms.service.AnswerRadioService;
import com.ofps.forms.service.OptionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

import static com.ofps.common.utils.SecurityUtils.getUserId;


@Service("answerRadioService")
public class AnswerRadioServiceImpl extends ServiceImpl<AnswerRadioMapper, AnswerRadio> implements AnswerRadioService {

    @Resource
    private AnswerRadioMapper answerRadioMapper;
    @Autowired
    private OptionService optionService;

    @Override
    public R save(HttpServletRequest request, AnswerRadio answerRadio) {
        //设置userId
//        answerRadio.setUserId(TokenUtil.getId(request));
//        answerRadio.setUserId(Math.toIntExact(getUserId()));

        //保存成功或失败
        return this.saveOrUpdate(answerRadio) ? R.ok("保存选择题答案成功！") : R.error("保存选择题答案失败！");
    }

    @Override
    public List<AnswerRadio> queryAnsRadiowithQuestionId(String Question_id) {
        QueryWrapper<AnswerRadio> answerRadioEntityQueryWrapper = new QueryWrapper<>();
        answerRadioEntityQueryWrapper.eq("question_id", Question_id);
        List<AnswerRadio> answerRadioList = answerRadioMapper.selectList(answerRadioEntityQueryWrapper);
        return answerRadioList;
    }

    @Override
    public Map<String, Object> summerizeRadioMessage(Map<String, Object> body) {
        List<AnswerRadio> answerRadioEntityList = new ArrayList<>();
        answerRadioEntityList = queryAnsRadiowithQuestionId(body.get("question_id").toString());
        //查询到的checkbox列表
        Map<String ,Object> summerizeMessages = new HashMap<>();
        Map <String,Map>TempSummerizeMessage = new HashMap<>();
        //汇总信息的列表
        Integer sum = 0;
        //计算所有的选择次数（用于计算百分比）
        List<Option> optionEntityList= optionService.queryWithId(body);
        sortByOrderId(optionEntityList,0,optionEntityList.size()-1);
        //System.out.println(optionEntityList);
        //获取选项信息
        List<String> Message = new ArrayList<>();
        for(Option optionEntity : optionEntityList){
            Message.add(optionEntity.getOrderId().toString());
            if (optionEntity.getContent().isEmpty() == false)
                Message.add(optionEntity.getContent());
            else
                Message.add("null");
            Message.add("0");
            Message.add("0");
        }
        //System.out.println(Message);
        System.out.println(answerRadioEntityList);
        for(AnswerRadio answerRadioEntity : answerRadioEntityList){
            Integer num = Integer.parseInt(answerRadioEntity.getOptionId().toString());
            //System.out.println("num:"+num.toString());
            Integer index = (num - 1) * 4 + 2;
            Integer newVal = Integer.parseInt(Message.get(index).toString()) + 1;
            Message.set(index,newVal.toString());
            sum++;
        }
        //System.out.println("answerListboxEntityList"+answerRadioEntityList.size());
        for (Integer i = 1 ; i < answerRadioEntityList.size()  ; i++){
            Integer index = (i - 1)*4 + 2;
            Integer num = Integer.parseInt(Message.get(index).toString());
            Float target = (num.floatValue()/sum.floatValue())*100;
            String Target = String.format("%.2f",target).toString() + "%";
            Message.set(index + 1,Target);
        }
        List<Map> structMessage = new ArrayList<>();

        for(int i = 0; i < Message.size() / 4 ; i++){
            Map<String,String> struct = new HashMap<>();
            struct.put("order_id",Message.get(i * 4 + 0));
            struct.put("order_information",Message.get(i * 4 + 1));
            struct.put("number",Message.get(i * 4 + 2));
            struct.put("percentage",Message.get(i * 4 + 3));
//            for(int j = 0; j < 4 ; j++){
//                struct.add(Message.get(i * 4 + j));
//            }
            structMessage.add(struct);
        }
        summerizeMessages.put("total_message",structMessage);
        summerizeMessages.put("sum",sum);
        summerizeMessages.put("type",1);
        return summerizeMessages;
//        List<AnswerRadioEntity> answerRadioEntityList= new ArrayList<>();
//        answerRadioEntityList = queryAnsRadiowithQuestionId(question_id);
//        Map<String , Object> summerizeMessage = new HashMap<>();
//        Map<String,Integer> summerizeOptions = new HashMap<>();
//        Map<String,Float> summerizeOptionsBypercentage = new HashMap<>();
//        Integer sum = 0;
//        for(AnswerRadioEntity answerRadioEntity:answerRadioEntityList){
//            if(summerizeOptions.containsKey(answerRadioEntity.getOptionId()) != true){
//                //表中不存在此元素
//                summerizeOptions.put(answerRadioEntity.getOptionId(), 1);
//            }
//            else{
//                //表中存在此元素
//                summerizeOptions.put(answerRadioEntity.getOptionId(),summerizeOptions.get(answerRadioEntity.getOptionId()) + 1);
//            }
//            sum++;
//        }
//        for(String key : summerizeOptions.keySet()){
//            Integer num = summerizeOptions.get(key);
//            Float percent = num.floatValue() / sum.floatValue() * 100;
//            //转换成百分比
//            summerizeOptionsBypercentage.put(key,percent);
//        }
//        summerizeMessage.put("summerizeRadioMessages",summerizeOptions);
//        summerizeMessage.put("sum",sum);
//        summerizeMessage.put("summerizeRadioMessagesByPercentage",summerizeOptionsBypercentage);
//        return summerizeMessage;
    }

    @Override
    public R delete(Map<String, Object> body) {
        //根据id查询删除
        QueryWrapper<AnswerRadio> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", body.get("id"));
        return answerRadioMapper.delete(queryWrapper) == 1 ? R.ok(20000, "删除成功！") : R.error(2000, "删除失败！");
    }
    private  void sortByOrderId(List<Option> list,Integer start,Integer end){
        if (start >= end) {
            return;
        }
        Option a =list.get(start);//定义基准值
        int i = start;//开始位置下标
        int j = end;//末尾位置下标
        while (i < j) {
            while (i<j && Integer.parseInt(list.get(j).getOrderId().toString())>=a.getOrderId()) {
                j--;
            }
            while (i<j && Integer.parseInt(list.get(i).getOrderId().toString())<=a.getOrderId()) {
                i++;
            }
            if (i<j) {//交换i和j的值
                Collections.swap(list,i,j);
            }
        }
        list.set(start,list.get(i));
        list.set(i,a);
        sortByOrderId(list, start, i-1);//递归调用
        sortByOrderId(list, i+1, end);
    }
}
